package ch.electronet.wjw.index;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Node implements NodeVisitable {

	private final Map<Integer, Node> children;
	private final Node parent;
	private final List data;
	private final int key;

	public Node() {
		this(null, -1);
	}

	public Node(Node parent, int key) {
		this.parent = parent;
		this.children = new LinkedHashMap<Integer, Node>();
		this.data = new LinkedList<Object>();
		this.key = key;
	}

	public boolean isLeaf() {
		return children.size() == 0;
	}

	public void add(String token, Object object) {
		if (token.length() == 0) {
			data.add(object);
		} else {
			int key;
			do {
				key = token.charAt(0);
				token = token.substring(1);
			} while (token.length() > 1 && key == ' ');

			Node child = children.get(key);
			if (child == null) {
				child = new Node(this, key);
			}
			child.add(token, object);
			children.put(key, child);
		}
	}

	public Node getParent() {
		return parent;
	}

	public Collection<Node> getChildren() {
		return children.values();
	}

	public Node getChild(int key) {
		return children.get(key);
	}

	public List getData() {
		return data;
	}

	public int getKey() {
		return key;
	}

	public void accept(NodeVisitor visitor) {
		visitor.visit(this);
	}

	public boolean isRoot() {
		return getKey() == -1;
	}
}
